import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
    Row, Col, Card, Form, Input,
    Select, Icon, Button, Dropdown, Menu,
    InputNumber, DatePicker, Modal, message,
    Badge, Divider, Tag, Table
} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './ProductCatalog.less';

const FormItem = Form.Item;
const { Option } = Select;
const { MonthPicker, RangePicker } = DatePicker;
/*
  产品管理的产品目录界面
*/

const stateArray = ["正常", "关闭"];
const productType = ["贷款", "分期"];

@connect(({ product }) => ({
    product,
    // loading: loading.models.rule,
}))
@Form.create()
export default class ProductCatalog extends PureComponent {
    state = {
        dataTimeFlag: false,
        modalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        dataTime: [],
        startTime: '',
        endTime: '',
    };
    componentDidMount() {
        const { dispatch } = this.props;
        dispatch({
            type: 'product/fetch',
            payload: { offset: 0, limit: 10 },
        });
    }

    handleStandardTableChange = (e) => {
        const { dispatch, form } = this.props;
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            dispatch({
                type: 'product/fetch',
                payload: {
                    offset: (e.current - 1) * e.pageSize,
                    limit: e.pageSize,
                    productName: fieldsValue.productName,
                    productNum: fieldsValue.productNum,
                    state: fieldsValue.status,
                    createTimeBegin: this.state.startTime,
                    createTimeEnd: this.state.endTime,
                },
            });
        });
        // this.props.dispatch({
        //     type: 'product/fetch',
        //     payload: { offset: (e.current - 1) * e.pageSize, limit: e.pageSize },
        // });
    }

    handleChangeTime = (dates, dateString) => {
        this.setState({
            dataTime: dateString,
            startTime: dates[0],
            endTime: dates[1],
        })
    }

    handleSearch = (e) => {
        e.preventDefault();
        const { dispatch, form } = this.props;
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            dispatch({
                type: 'product/fetch',
                payload: {
                    offset: 0,
                    limit: 10,
                    productName: fieldsValue.productName,
                    productNum: fieldsValue.productNum,
                    state: fieldsValue.status,
                    createTimeBegin: this.state.startTime,
                    createTimeEnd: this.state.endTime,
                },
            });
        });
    }

    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        this.setState({
            dataTimeFlag: false,
            formValues: {},
            dataTime: [],
            startTime: '',
            endTime: '',
        });
        dispatch({
            type: 'product/fetch',
            payload: {
                offset: 0,
                limit: 10,
            },
        });
    }

    renderSimpleForm() {
        const { getFieldDecorator } = this.props.form;

        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={10} sm={24}>
                        <FormItem label="产品名称" >
                            {getFieldDecorator('productName')(
                                <Input placeholder="请输入" style={{ width: '100%' }}/>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={10} sm={24}>
                        <FormItem label="产品编号" >
                            {getFieldDecorator('productNum')(
                                <Input placeholder="请输入" style={{ width: '100%' }}/>
                            )}
                        </FormItem>
                    </Col>
                </Row>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={10} sm={24}>
                        <FormItem label="创建时间" >
                            {getFieldDecorator('createTime')(
                                <div>
                                    <RangePicker 
                                        allowClear={true}
                                        showToday={true}
                                        onChange={this.handleChangeTime}
                                        style={{ width: '100%' }}
                                        value={[
                                            this.state.dataTimeFlag ? null : this.state.startTime,
                                            this.state.dataTimeFlag ? null : this.state.endTime
                                          ]}
                                        showTime={{ hideDisabledOptions: true }}
                                        format="YYYY-MM-DD HH:mm:ss"
                                    />
                                </div>,
                            )}
                        </FormItem>
                    </Col>
                    <Col md={10} sm={24}>
                        <FormItem label="状态" >
                            {getFieldDecorator('status')(
                                <Select placeholder="请选择" style={{ width: '100%' }}>
                                    <Option value="0">打开</Option>
                                    <Option value="1">关闭</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                  
                    <span className={styles.submitButtons} style={{ textAlign: 'right' }}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
                    </span>
                </Row>                
            </Form>
        );
    }

    columns = [{
        title: '产品编号',
        dataIndex: 'productNum',
        key: 'productNum',
    }, {
        title: '产品名称',
        dataIndex: 'productName',
        key: 'productName',
    }, {
        title: '产品规模',
        dataIndex: 'productSize',
        key: 'productSize',
    }, {
        title: '产品种类',
        dataIndex: 'productType',
        key: 'productType',
        render(val) {
            return productType[val];
        },
    }, {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
    }, {
        title: '状态',
        dataIndex: 'state',
        key: 'state',
        render(val) {
            return stateArray[val];
        },
    }, {
        title: '操作',
        dataIndex: 'id',
        // key: 'id',
        render: (text, record) => (
            //0:打开；1：关闭；
            <Fragment>
                <a href={`/#/product/product-details?id=${record.id}`}>详情</a>
                <Divider type="vertical" />
                {
                    record.state == '0' ? <a onClick={() => this.handleSetState(record, 1)}>关闭</a>
                        :
                        <a onClick={() => this.handleSetState(record, 0)}>打开</a>
                }
            </Fragment>
        ),
    }];

    handleSetState = (record, newState) => {
        // console.log("wwwwwww")
        // console.log(record)
        this.props.dispatch({
            type: 'product/changeProductState',
            payload: {
                id: record.id,
                state: newState
            },
            callback: () => {
                this.props.dispatch({
                    type: 'product/fetch',
                    payload: {
                        offset: 0,
                        limit: 10,
                    },
                });
            },
        });
    }

    render() {
        const { product: { productList, page, loading }, dispatch } = this.props;
        const { getFieldDecorator } = this.props.form;

        const onValidateForm = () => {
            dispatch(routerRedux.push('/product/product-add'));
        };

        return (
            <PageHeaderLayout title="产品列表">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            {this.renderSimpleForm()}
                        </div>
                        <div className={styles.tableListOperator}>
                            <Button icon="plus" type="primary" onClick={onValidateForm}>
                                添加产品
                            </Button>
                        </div>
                        {/* aaaa{JSON.stringify(productList)}ssss */}
                       
                        <Table
                            bordered
                            dataSource={productList}
                            columns={this.columns}
                            rowKey="id"
                            pagination={page}
                            loading={loading}
                            onChange={this.handleStandardTableChange}
                        />
                    </div>
                </Card>
            </PageHeaderLayout>
        );
    }
}